package com.xiaocikuai.smallchunks.file;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.PutObjectRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Service
public class PutObject004 {

    private static final String ENDPOINT = "https://obs.cn-north-4.myhuaweicloud.com";

    private static final String AK = "QPBSU49CZFWDJHWNIDZM";

    private static final String SK = "9Y3Bex5SCialvY53JVeZJZTywfORxyI7Xig6iKH3";
    private static final String BUCKET_NAME = "xck-datas";

    private static String getEnvVar(String key) {
        String value = System.getenv(key);
        if (value == null || value.isEmpty()) {
            throw new IllegalArgumentException("Environment variable " + key + " is not set.");
        }
        return value;
    }


    public String uploadFile(MultipartFile file, String filePath) {

        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(AK, SK, ENDPOINT);

        try {

            // 新文件名
            String newFileName = UUID.randomUUID().toString() + "_" + file.getName();
            String objectKey = filePath + "/" + newFileName;

            File tempFile = convertMultipartFileToFile(file);



            // 文件上传
            PutObjectRequest request = new PutObjectRequest();
            request.setBucketName(BUCKET_NAME);
            request.setObjectKey(objectKey);
            request.setFile(tempFile);
            obsClient.putObject(request);
            System.out.println("putObject successfully");
            tempFile.delete();
            // 返回文件链接
            return "https://xck-datas.obs.cn-north-4.myhuaweicloud.com" + "/" + objectKey;
        } catch (ObsException e) {
            System.out.println("putObject failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            System.out.println("putObject failed");
            // 其他异常信息打印
            e.printStackTrace();
            return null;
        }
    }

    private File convertMultipartFileToFile(MultipartFile file) throws IOException {
        File convFile = new File(System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename());
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
    }
}
